package com.woniu.payback_font.web;

import com.github.pagehelper.PageInfo;
import com.woniu.payback_font.entity.Load;
import com.woniu.payback_font.entity.LoanApplication;
import com.woniu.payback_font.entity.Repayment;
import com.woniu.payback_font.result.ResponseResult;
import com.woniu.payback_font.service.AccountService;
import com.woniu.payback_font.service.LoadService;
import com.woniu.payback_font.service.RepaymentPlanService;
import com.woniu.payback_font.service.RepaymentService;
import com.woniu.payback_font.vo.LoanVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("loanApplication")
@Api(value = "借款申请api接口")
public class LoanController {

    @Autowired
    private LoadService loadService;

    @Autowired
    private RepaymentService repaymentService;

    @Autowired
    private RepaymentPlanService repaymentPlanService;

    @Autowired
    private AccountService accountService;

    //查询借款申请的信息
    @GetMapping("/showLoanAppplications")
    public ResponseResult<PageInfo<LoanApplication>> showLoanAppplications(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum ,
                                                                           @RequestParam(value = "pageSize",defaultValue = "4")Integer pageSize,
                                                                           String laName,
                                                                           String laMobile,
                                                                           String laIdcard,
                                                                           String laInvestorName,
                                                                           Integer laLoadApplicationStatus){

        ResponseResult result = new ResponseResult();
        PageInfo<LoanApplication> pageInfo = loadService.dynamicPageSeach(pageNum, pageSize, laName,laMobile,laIdcard,laInvestorName,laLoadApplicationStatus);
        result.setData(pageInfo);
        result.setCode(200);
        result.setMsg("查询成功");
        return result;
    }

    /**
     * LoanVo(status=1, lId=1, lUid=yonghu1, lName=马冬梅, lIdcard=12345678, lMobile=123456, lProductName=戴去花, lReceiptNo=111111111,
     * lLoadStatus=1, lCreditLimit=null(不插入), lUsedLimit=null, lLoadStartTime=Wed Sep 01 08:00:00 CST 2021, lStagesNum=12, lLoadSettle=null,
     * lLoadMoney=100000, lIntestall=null, lRepaymentMethod=1,lRate=null(前端不展示), lScore=null(前端不展示), lInvestorName=钻石交易金融, lLoadCollectionTime=null,
     * lCollectionBankcard=25723421212)
     */
    @Transactional
    @PutMapping("/examine")
    public ResponseResult<Void> examine(@RequestBody LoanVo loanVo){
        ResponseResult result = new ResponseResult<>();
        loanVo.setlProductName("戴去花");
        int row = 0;//判断是否插入成功
        //通过status字段判断执行的是通过审批还是拒绝审批.(1:通过,0:拒绝)
        try {
            if (loanVo.getStatus()==1){//通过审批
                //1.修改借款人审批状态
                loanVo.setlLoadStatus(1);
                //2.将审批通过的额度更新到已使用额度中
                loanVo.setlUsedLimit(loanVo.getlLoadMoney());//借款金额就是已用信用额度
                //3.初始化借款发起时间
                loanVo.setlLoadStartTime(new Date());
                //4.设置到账时间(五分钟后)
                Calendar nowTime = Calendar.getInstance();
                nowTime.add(Calendar.MINUTE, 5);
                loanVo.setlLoadCollectionTime(nowTime.getTime());
                //5.初始化还款状态为0,未还款
                loanVo.setlLoadSettle(0);
                //6.查询t_repayment总利息并且放入vo属性中
                String lReceiptNo = loanVo.getlReceiptNo();
                loanVo.setlIntestall(repaymentService.queryIntestAll(lReceiptNo));
                //7.每一条loan表中的一条记录对应唯一一个借据号,t_repayment表中多条借款信息.
                row = loadService.addLoan(loanVo);

                /**
                 *金额审批之后更新t_account表如下字段:
                 *欠款额度:  aUsedLimit;
                 *借款本金:  aDebtCapita;
                 *欠款总利息: aDebtInterest;
                 *还款天数:  aRepaymentDate
                 */
                BigDecimal aDebtCapita = repaymentPlanService.queryAllCapital(loanVo.getlUid());
                BigDecimal aDebtInterest = repaymentPlanService.queryAllInterest(loanVo.getlUid());
                BigDecimal aUsedLimit = aDebtCapita.add(aDebtInterest);//欠款总额=欠款利息+欠款本金
                Integer aRepaymentDate = (int)(Math.random()*28+1);
                accountService.modify(aDebtCapita,aDebtInterest,aUsedLimit,aRepaymentDate);

            }else if (loanVo.getStatus()==0){//添加拒绝审批的记录
                //1.修改借款人审批状态
                loanVo.setlLoadStatus(0);//借款失败
                //3.初始化借款发起时间
                loanVo.setlLoadStartTime(new Date());
                System.out.println(loanVo);
                row = loadService.addfalseLoan(loanVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(loanVo);

        if (row == 1){
            result.setMsg("查询成功");
            result.setCode(200);
        }
        return result;
    }


    /**
     *  借款列表查询接口
     * @param pageNum
     * @param pageSize
     * @param lName
     * @param lMobile
     * @param lReceiptNo
     * @param lProductName
     * @param lInvestorName
     * @return
     */
    @GetMapping("/showLoan")
    public ResponseResult<PageInfo<Load>> showLoan(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum ,
                                                              @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
                                                                           String lName, String lMobile, String lReceiptNo, String lProductName, String lInvestorName){
        ResponseResult result = null;
        PageInfo<Load> info = loadService.findByPrimarydata(pageNum, pageSize, lName, lMobile, lReceiptNo, lProductName, lInvestorName);
        if(info==null){
            result=new ResponseResult(204,"查询失败");
        }else{
            result=new ResponseResult(200,"查询成功");
            result.setData(info);
        }
        return result;
    }


    /**
     *  借款详情查询接口（显示单条数据）
     * @return
     */
    @GetMapping("/showOneLoan/{lId}")
    public ResponseResult<Load> showOneLoan(@PathVariable("lId")Integer lId){
        ResponseResult result = null;
        Load load = loadService.findOne(lId);
        if(load==null){
            result=new ResponseResult(204,"查询失败");
        }else{
            result=new ResponseResult(200,"查询成功");
            result.setData(load);
        }
        return result;
    }

    /**
     *  查看分期详情代码
     * @return
     */
    @GetMapping("/findLoadList")
    public ResponseResult<PageInfo<Repayment>> findLoadList(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum ,
                                                            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
                                                            String lReceiptNo){
        ResponseResult result = null;
        PageInfo<Repayment> info = repaymentService.findLoadList(pageNum,pageSize,lReceiptNo);
        if(info==null){
            result=new ResponseResult(204,"查询失败");
        }else{
            result=new ResponseResult(200,"查询成功");
            result.setData(info);
        }
        return result;
    }



    /**
     *  查看分期详情代码
     * @return
     */
    @GetMapping("/showUserLoan")
    public ResponseResult<PageInfo<Load>> showUserLoan(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum ,
                                                            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
                                                            String aUid){
        ResponseResult result = null;
        PageInfo<Load> info = loadService.showUserLoan(pageNum,pageSize,aUid);
        if(info==null){
            result=new ResponseResult(204,"查询失败");
        }else{
            result=new ResponseResult(200,"查询成功");
            result.setData(info);
        }
        return result;
    }

    public static void main(String[] args) {
//        System.out.println((int)(Math.random()*28+1));
    }

}
